using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;

namespace Voodoo.Sauce.Internal.CrossPromo.Canvas
{
	internal class DefaultFormat : AFormatManager
	{
		private Text _gameName;

		private VideoManager _videoManager;

		[SerializeField]
		private GameObject _adLabel;

		private void Awake()
		{
			AFormatManager.Instance = this;
			base.gameObject.name = "CrossPromoGameObject";
			CrossPromoEvents.ShowEvent += ((AFormatManager)this).Display;
			CrossPromoEvents.HideEvent += ((AFormatManager)this).Hide;
		}

		private void OnDestroy()
		{
			CrossPromoEvents.ShowEvent -= ((AFormatManager)this).Display;
			CrossPromoEvents.HideEvent -= ((AFormatManager)this).Hide;
		}

		private void Start()
		{
			try
			{
				_videoManager = new VideoManager(GetComponentInChildren<VideoPlayer>(), GetComponentInChildren<RawImage>());
				_gameName = GetComponentInChildren<Text>();
				_videoManager.VideoPlayer.prepareCompleted += delegate
				{
					if (Asset == null)
					{
						Hide();
					}
					else
					{
						Enable(show: true);
						VoodooCrossPromo.Callback.ShownEvent(Asset);
					}
				};
				Enable(show: false);
			}
			catch (Exception ex)
			{
				VoodooLog.LogE(VoodooCrossPromo.TAG, ex.ToString());
			}
		}

		public override void Display()
		{
			if (IsWaiting)
			{
				IsActive = true;
			}
			if (!IsActive && !IsWaiting)
			{
				StartCoroutine(StartDisplay());
			}
		}

		private IEnumerator StartDisplay()
		{
			IsActive = true;
			IsWaiting = true;
			yield return new WaitForEndOfFrame();
			yield return WaitCrossPromoReady(_videoManager);
			IsWaiting = false;
			if (IsActive && Asset != null)
			{
				if (Asset.game.name != null)
				{
					_gameName.text = Asset.game.name;
				}
				try
				{
					_videoManager.PrepareVideo(Asset);
				}
				catch (Exception message)
				{
					VoodooCrossPromo.Callback.ErrorEvent(message);
				}
			}
		}

		public override void Hide()
		{
			IsActive = false;
			Asset = null;
			if (_videoManager != null)
			{
				_videoManager.StopVideo();
				Enable(show: false);
			}
		}

		private void Enable(bool show)
		{
			GetComponent<Image>().enabled = show;
			base.transform.GetChild(0).gameObject.SetActive(show);
			base.transform.GetChild(1).GetComponentInChildren<Image>().enabled = show;
			_adLabel.SetActive(show);
		}
	}
}
